<script lang="ts" setup>
import { ref, reactive, computed } from "vue";
import { PermissionApi } from "@/Api";

interface Props {
   modelValue: boolean;
   valueId?: string;
}

const props = withDefaults(defineProps<Props>(), {
   modelValue: false
});

const emit = defineEmits<{
   (e: "update:modelValue", value: boolean): void;
}>();

const dialogVisible = computed({
   get: () => props.modelValue,
   set: value => emit("update:modelValue", value)
});

const valueId = computed(() => props.valueId);

const loading = reactive({ add: false, dialog: false });
const disable = reactive({ add: false });
const treeData = ref();
const actionIds = ref<string[]>([]);

/**
 * 分配权限
 * @param id 当前角色 id
 * @param keys 路由 id 集合
 */
async function handlerCLick(keys: string[], id?: string) {
   if (!id) return;

   try {
      const { code } = await PermissionApi.Assign({ role_id: id, ids: keys });
      if (code === 200) {
         ElMessage.success("修改成功");
         dialogVisible.value = false;
         actionIds.value = [];
      }
   } catch (error) {
      console.log("error", error);
   }
}

function handleCheck(node: Permission.Tree, checked: Permission.Checked) {
   actionIds.value = checked.checkedKeys;
}

/** 查询当前角色权限 */
async function searchPermission(id?: string) {
   if (!id) return ElMessage.error("系统错误，请重试");
   loading.dialog = true;

   try {
      const { code, data } = await PermissionApi.Search({ role_id: id });
      if (code === 200) {
         treeData.value = data.tree;
         actionIds.value = data.ids;
      }
   } catch (error) {
      console.log("error", error);
   }

   loading.dialog = false;
}

/** 弹窗打开时 */
function handlerOpen() {
   searchPermission(valueId.value);
}

function handlerClose() {
   actionIds.value = [];
}
</script>

<template>
   <el-dialog
      v-model="dialogVisible"
      ref="dialog"
      title="分配权限"
      width="500px"
      draggable
      append-to-body
      @open="handlerOpen"
      @closed="handlerClose">
      <template #default>
         <el-tree
            ref="treeRef"
            v-loading="loading.dialog"
            :data="treeData"
            node-key="id"
            :default-checked-keys="actionIds"
            @check="handleCheck"
            show-checkbox
            default-expand-all
            check-strictly
            :props="{
               label: 'meta_label'
            }" />
      </template>
      <template #footer>
         <span class="dialog-footer">
            <el-button :loading="loading.add" :disabled="disable.add" type="primary" @click="handlerCLick(actionIds, valueId)">
               保存
            </el-button>
         </span>
      </template>
   </el-dialog>
</template>

<style lang="scss" scoped>
.el-form {
   box-sizing: border-box;
   padding-inline: 20px;
}
.el-input {
   width: 100%;
}
</style>
